<?php

/**
 * 从mongo同步小区数据
 */

namespace app\crontab\controller\once;


use custom\Log;
use custom\Mongo;
use custom\Redis;
use map\BaiDu;
use map\GaoDe;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

class HouseVillage2 extends Command {

    protected function configure() {
        $this->setName('HouseVillage2');
    }

    protected function execute(Input $input, Output $output) {
        $this->initial();
    }

    /**
     * 小区-同步
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function initial() {
        echo "runing\n";
        set_time_limit(0);//防止超时
        ini_set("memory_limit", "512M");//防止内存溢出
        $mongo = Mongo::getInstance();
        $city = '成都,西安,重庆,武汉';
        $city = explode(',', $city);
        $cursor = $mongo->select('ajk_xiaoqu_url', ['city' => ['$in' => $city]], []);
        $total = count($cursor);
        print_r($total . "\n");
        $num = $a = 0;
        $redisModel = Redis::getInstance();
        foreach ($cursor as $key => $value) {
            $value = (array)$value;
            $addr = $value['address'] ? $value['address'] : $value['name'];
            $city = $this->getRegionCode($value['city'], $value['area'], $value['business_area']);
            $business_id = $city['business_id'];//商圈id
            $anju = rtrim($value['source_url'], '/');
            $anju = explode('/', $anju);
            $anju_id = end($anju);//安居客id
            $data = [
                'location'       => Db::raw("POINT(0, 0)"),
                'lng'            => 0,
                'lat'            => 0,
                'name'           => $value['name'],//小区名称
                'cover'          => '', //封面图
                'address'        => $value['address'],
                'price_unit_avg' => $value['price'] ?? 0,//参考价
                'itime'          => time(),//创建时间
                'month_itime'    => strtotime(date('Y-m', time())),
                'day_itime'      => strtotime(date('Y-m-d', time())),
                'business_area'  => $business_id, //商圈id
                'city_code'      => $city['city_id'],//区域code
                'city_codes'     => $city['city_ids'],//城市编码集合
                'source_url'     => $value['source_url'] ?? '',
                'province'       => $city['province'],//省
                'city'           => $city['city'],//市
                'area'           => $city['area'],//区
                'business_name'  => $value['business_area'],//商圈名称
                'source_id'      => !is_numeric($anju_id) ? '' : $anju_id,//来源id
                '_id'            => $value['_id'],
            ];

            // 处理500条数据
            $num++;
            $res[] = $data;
            if ($num >= 500) {
                echo "500\n";
                $a += Db::name("cs_house_village")->insertAll($res);
                $res = [];
                $num = 0;
            }

        }

        if (!empty($res)) {
            $a += Db::name("cs_house_village")->insertAll($res);
        }
        $redisModel->del('err_housevillage_addre');
        $redisModel->del('err_housevillage_code');
        echo "end\n";
        echo "total:" . $total . "\n";
        echo 'success:' . $a . "\n";
        Log::write("total->$total;success->$a", "HouseVillage2.log");
    }

    /**
     * 小区-地图
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function map() {
        $total = 0;
        while (true) {
            $num = 0;
            $datas = Db::name("house_village")->where('lng', 0)->limit(100)->select();
            if (empty($datas)) {
                echo "end||total:{$total}";
                exit;
            }
            foreach ($datas as $k => $value) {
                $addr = $value['name'];
                if (in_array($value['business_name'], ['彭山', '仁寿', '其它'])) {
                    $value['city'] = '成都';
                }

                $arr = $this->getAddressInfoByMap($addr, $value['city'], $value['address']);
                $data = [
                    // 地图
                    'location' => Db::raw("POINT('{$arr['lng']}', '{$arr['lat']}')"),
                    'lng'      => $arr['lng'],
                    'lat'      => $arr['lat'],
                ];
                if ($arr['lng'] > 0 && $arr['lat'] > 0) {
                    $num += db('house_village')->where('id', $value['id'])->update($data);
                } else {
                    echo "{$value['name']}||{$value['id']}\n";
                }

            }
            $total += $num;
            echo "num:{$num}\n";
        }

    }

    /**
     * 百度-获取详细信息
     * @param $address
     * @param string $city
     * @return array
     * @throws Exception
     */
    public function getAddressInfoByMap($address, $city = '', $address_name) {
        //通过地址解析经纬度
        $lng = $lat = 0;
        $res = BaiDu::placeSearch($address, $city, '住宅');
        if (!empty($res['results'][0]['location']['lng']) && !empty($res['results'][0]['location']['lat'])) {

            $lng = round($res['results'][0]['location']['lng'], 6);
            $lat = round($res['results'][0]['location']['lat'], 6);
        }


        if ($lng <= 0 || $lat <= 0) {
            // 调用高德地图
            $res = GaoDe::getPoi($address, $city, '');
            if (!empty($res['pois'][0]['location'])) {
                $location = explode(',', $res['pois'][0]['location']);
                $lng = $location[0];
                $lat = $location[1];
            }
        }

        if ($lng <= 0 || $lat <= 0) {
            // 调用高德地图,用地址查询
            $res = GaoDe::getPoi($address_name, $city, '');
            if (!empty($res['pois'][0]['location'])) {
                $location = explode(',', $res['pois'][0]['location']);
                $lng = $location[0];
                $lat = $location[1];
            }
        }

        if ($lng <= 0 || $lat <= 0) {
            $lng = $lat = 0;
        }

        $data = [
            'lng' => $lng,
            'lat' => $lat,
        ];
        return $data;
    }

    /**
     * 获取城市code
     * @param $city
     * @param $area
     * @return array
     */
    public function getRegionCode($city, $area, $business_area) {
        $city_rank2 = db('region')->where("name like '{$city}%' and rank=2")->find();
        $re = db('region')->field('city_code,p_code,p_codes,pids,name')->where("name like '{$area}%' and p_codes like '{$city_rank2['p_codes']}%'")->where('rank', 3)->find();
        if (!$re) {
            $data = array(
                'city_id'     => 0,
                'city_ids'    => '',
                'province'    => '',
                'city'        => '',
                'area'        => '',
                'business_id' => 0
            );
            $redisModel = Redis::getInstance();
            $is_or = $redisModel->hget('err_housevillage_code', $city . '-' . $area);
            if (!$is_or) {
                $redisModel->hset('err_housevillage_code', $city . '-' . $area, $area);//查不到城市code的商圈存入redis
                Log::write("小区未找到城市区域数据;city->{$city},area->{$area}", "HouseVillage2.log");
            }

        } else {
            $pids = trim($re['pids'], ",");
            $name = db('region')->field('name,rank')->where("id in ($pids)")->select();
            $business_id = db('cs_business_area')->where('name', $business_area)->where('city_id', $re['city_code'])->value('id');
            if (empty($business_id)) {
                $business_id = 0;
                Log::write("未找到商圈数据;city->{$city},area->{$area},business_area->{$business_area}", "cs_business_area_data.log");
            }

            $province = $city = $area = '';
            foreach ($name as $key => $value) {
                if ($value['rank'] == 1) {
                    $province = $value['name'];
                }
                if ($value['rank'] == 2) {
                    $city = $value['name'];
                }


            }
            $data = array(
                'city_id'     => $re['city_code'],
                'city_ids'    => $re['p_codes'] . $re['city_code'] . ',',
                'province'    => $province,
                'city'        => $city,
                'area'        => $re['name'],
                'business_id' => $business_id
            );
        }

        return $data;
    }
}